package 并发编程16.消息发送场景;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author idea
 * @data 2019/2/10
 */
public class Message implements Delayed {

    private int id;
    /**
     * 消息内容
     */
    private String body;

    /**
     * 延迟时长
     */
    private long excuteTime;

    public Message(int id, String body, long excuteTime) {
        this.id = id;
        this.body = body;
        this.excuteTime = excuteTime;
    }

    /**
     * 当这里返回小于等于0的值的时候，表示该元素已经到期了
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        long time = unit.convert(this.excuteTime - System.nanoTime(), TimeUnit.NANOSECONDS);
        System.out.println(time);
        return time;
    }

    /**
     * 这个是延迟队列里面元素先后顺序的判断核心步骤
     *
     * @param delayed
     * @return
     */
    @Override
    public int compareTo(Delayed delayed) {
        Message msg = (Message) delayed;
        return Integer.valueOf(this.id) > Integer.valueOf(msg.id) ? 1
                : (Integer.valueOf(this.id) < Integer.valueOf(msg.id) ? -1 : 0);
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", body='" + body + '\'' +
                ", excuteTime=" + excuteTime +
                '}';
    }

    public int getId() {
        return id;
    }

    public Message setId(int id) {
        this.id = id;
        return this;
    }

    public String getBody() {
        return body;
    }

    public Message setBody(String body) {
        this.body = body;
        return this;
    }

    public long getExcuteTime() {
        return excuteTime;
    }

    public Message setExcuteTime(long excuteTime) {
        this.excuteTime = excuteTime;
        return this;
    }
}
